import webapp2
from google.appengine.ext import db
from google.appengine.api import users
from datatypes import *
import logger
    
def UserFromSession():
    return users.get_current_user()

def isUserLoggedIn():
    return False if not UserFromSession() else True

def nameFromUserModel():
    return ourUserModel().username

def isRegistered():
    current_user = UserFromSession()
    if current_user:
        regUsers = User.all().ancestor(
            UserPathGen()).filter('user_id =', current_user.user_id())
        return regUsers.count() == 1
    else:
        return False

def isAdmin():
    if not isRegistered():
        return False
    else:
        user = User.all().ancestor(
            UserPathGen()).filter('user_id =', UserFromSession().user_id())
        person = user.get()
        return person.isAdmin

def adminOrGtfo(requesthandler):
    if not isAdmin():
        requesthandler.response.status = '401 Forbidden'
        requesthandler.response.out.write("Thou shalt not pass")
        logger.log("Attempted admin command by non-admin: {0}".format(
            nameFromUserModel()))
        return True
    else:
        return False

def ourUserModel():
    usr_session = UserFromSession()
    qUsers = User.all().ancestor(
        UserPathGen()).filter('user_id =', usr_session.user_id())
    return qUsers.get()


